* ---------------------------------------- *
* Trace and label variables 
* ---------------------------------------- *

* hasvar adds "\yes" or "\no" to a local given by the `local` option depending on whether at least one of the given variables is part of the model.
cap program drop hasvar
program hasvar, eclass
	syntax varlist, local(string) [yes(string) No(string)]
	
	// Defaults:
	if "`yes'" == "" {
		local yes "\yes"
	}
	if "`no'" == "" {
		local no "\no"
	}

	local a 0
	local lst `e(indepvars)'
	foreach var in `varlist' {
		local x : list posof "`var'" in lst
		local a = `a' + `x'
	}
	if `a' > 0 {
		ereturn local has_`local'="`yes'"
	}
	else {
		ereturn local has_`local'="`no'"
	}
end program

* Set the default labels for our paper.


cap program drop make_label
program make_label
    local len : word count `varlabels'
    forvalues i = 1/`len' {
        local var : word `i' of `vars'
        local lbl : word `i' of `varlabels'
        local lbl "\nsk `lbl'"
        cap gen `var' = .
        label var `var' "`lbl'"
    }
end program


cap program drop setlabels
program setlabels
	* BASE VARIABLES
	syntax , [sname(string)]
	if "`sname'" == "" {
		local sname "automation"
	}
	// baseline variables
	local vars LSW HSW MSW LMSW MINW LSWHSW ISP GDPGAP VAEMP GDPPC stockown stockother spilloversown spilloversother
	local varlabels `""Low-skill wage" "High-skill wage" "Middle-skill wage" "Low and middle-skill wage" "Minimum wage" "Low-skill / High-skill wages" "Low-skill / High-skill wages" "GDP gap" "Labor productivity" "GDP per capita" "Stock `sname'" "Stock other" "Spillovers `sname'" "Spillovers other""'
      local len : word count `varlabels'
    forvalues i = 1/`len' { 
        local var : word `i' of `vars'
        local lbl : word `i' of `varlabels'
        local lbl "\nsk `lbl'"
        cap gen `var' = .
        label var `var' "`lbl'"
    }
	
	// macro simulation variables
	local vars stockauto95 stocktfam95 stockpauto95 spilloversauto95 spilloverstfam95 spilloverspauto95 sqspilloversauto95 sqspilloverspauto95 sqspilloversother spillovers_inter
	local varlabels `" "Stock automation" "Stock mach.\textbackslash{}auto95" "Stock non-automation" "Spillovers automation" "Spillovers mach.\textbackslash{}auto95" "Spillovers non-automation" "Spillovers automation squared" "Spillovers non-automation squared" "Spillovers other squared" "Spillover interaction" "'
      local len : word count `varlabels'
    forvalues i = 1/`len' {
        local var : word `i' of `vars'
        local lbl : word `i' of `varlabels'
        local lbl "\nsk `lbl'"
        cap gen `var' = .
        label var `var' "`lbl'"
    }
	
	// inventor weighted wages + additional controls ("ovb")
	local vars LSWiw HSWiw GDPGAPiw VAEMPiw GDPPCiw Lintr mshare offshoring msize spilloversownpw spilloversotherpw LSW_l2 HSW_l2 LSW_lj HSW_lj mVAlsm_1995_a mVAlmsm_1995_a mVAemplsm_1995_a mVAemplmsm_1995_a
	local varlabels  `""Low-skill wage (iw)" "High-skill wage (iw)" "GDP gap (iw)" "Labor productivity (iw)" "GDP per capita (iw)" "Long-term interest rate" "Manufacturing share" "Offshoring" "Manufacturing size" "Recent auto95 innovation" "Recent other innovation" "Low-skill wage (L2)" "High-skill wage (L2)" "Low-skill wage (Lj)" "High-skill wage (Lj)" "\mrmc{Manufacturing size \\ (low-skill weighted)}" "\mrmc{Manufacturing size \\ (low- and middle-skill weighted)}" "\mrmc{Labor productivity \\ (low-skill weighted)}" "\mrmc{Labor productivity \\ (low-and middle-skill weighted)}" "'
      local len : word count `varlabels'
    forvalues i = 1/`len' {
        local var : word `i' of `vars'
        local lbl : word `i' of `varlabels'
        local lbl "\nsk `lbl'"
        cap gen `var' = .
        label var `var' "`lbl'"
    }

	// longdifference variables
	local vars D_LSW D_HSW D_GDPGAP D_VAEMP D_GDPPC D_ISP D_LSWHSW D_spilloversauto D_spilloversnonauto D_spilloversnonmach
	local varlabels `""$\Delta$ Low-skill wage" "$\Delta$ High-skill wage" "$\Delta$ GDP gap" "$\Delta$ Labor productivity" "$\Delta$ GDP per capita" "$\Delta$ Low-skill / High-skill wages" "$\Delta$ Low-skill / High-skill wages" "$\Delta$ Spillovers Auto" "$\Delta$ Spillovers Nonauto" "$\Delta$ Spillovers Nonmach" "'

	local len : word count `varlabels'
    local len : word count `varlabels'
    forvalues i = 1/`len' {
        local var : word `i' of `vars'
        local lbl : word `i' of `varlabels'
        local lbl "\nsk `lbl'"
        cap gen `var' = .
        label var `var' "`lbl'"
    }

	// placebo / auto-pauto control variables
	local vars Placebo Placebozero Logpauto90 Anypauto90 Arcsinhpauto90 Logplacebo Anyplacebo
	local varlabels  `" "Placebo innovations" "No placebo innovations" "Log pauto90" "Any pauto90" "Arcsinh pauto90" "Log placebo machinery" "Any placebo machinery" "'
    local len : word count `varlabels'
    forvalues i = 1/`len' {
        local var : word `i' of `vars'
        local lbl : word `i' of `varlabels'
        local lbl "\nsk `lbl'"
        cap gen `var' = .
        label var `var' "`lbl'"
    }

	// hartz exercise variables
	local vars post_exposure_trend_auto exposure_trend_auto exposure_trend post_exposure_trend
	local varlabels  `" "Time trend \stimes auto95 dummy \stimes German exposure \stimes post" "Time trend \stimes auto95 dummy \stimes German exposure" "Time trend \stimes German exposure" "Time trend \stimes German exposure \stimes post" "'
    local len : word count `varlabels'
    forvalues i = 1/`len' {
        local var : word `i' of `vars'
        local lbl : word `i' of `varlabels'
        local lbl "\nsk `lbl'"
        cap gen `var' = .
        label var `var' "`lbl'"
    }

	// ALM / industry level variables
	local vars sh_auto sh_auto_use sh_auto_mk computeruse manuf ln_auto95_use ln_pauto95_use ln_auto95_mk ln_pauto95_mk ln_emp_init_alm 
	local varlabels  `" "Share automation" "\mrmc{Share automation \\ (using industry)}" "\mrmc{Share automation \\ (inventing industry)}" "\mrmc{$\Delta$ Computer use \\ (1984-1997)}" "Manufacturing" "\mrmc{Log automation patents \\ (using industry)}" "\mrmc{Log non-automation patents \\ (using industry)}" "\mrmc{Log automation patents \\ (inventing industry)}" "\mrmc{Log non-automation patents \\ (inventing industry)}" "Log initial employment" "'
	  local len : word count `varlabels'
    forvalues i = 1/`len' {
        local var : word `i' of `vars'
        local lbl : word `i' of `varlabels'
        local lbl "\nsk `lbl'"
        cap gen `var' = .
        label var `var' "`lbl'"
    }
    // note that \mrmc is a custom latex command (due to statas character length limit for var labels)

	// predicting weights
	local vars g_lsw_5yr_1995 g_hsw_5yr_1995
	local varlabels  `" "Growth in low-skill wages, 1995-2000" "Growth in high-skill wages, 1995-2000" "'
	  local len : word count `varlabels'
    forvalues i = 1/`len' {
        local var : word `i' of `vars'
        local lbl : word `i' of `varlabels'
        local lbl "\nsk `lbl'"
        cap gen `var' = .
        label var `var' "`lbl'"
    }

end program

* ---------------------------------------- *
* DHOZTAB wrapper
* ---------------------------------------- *

* dhoztab is a wrapper to esttab, which creates tables in the format of the DHOZ paper.
* Syntax corresponds to esttab. Custom LaTeX is added. The wrapper produces compilable latex documents.
* Additionally, the required option depvar indicates the name of the depdendent variable in the model. Write "none" to indicate no depvar.
* Further, the program supports a custom 'note' option which adds notes in a tablenotes latex environment.

cap program drop dhoztab
program dhoztab
	syntax anything [using], [notes(string) depvarlist(passthru) rawaddheader(passthru) m(string) nopvalues showdepvarinfo depvar(string)] *

    * Prehead: packages, begindocument, begintable, depvarinfo, rawaddaddheader

    local packages = "`packages'%------- Packages and Set up ------- %" + char(10)
    local packages = "`packages'" + char(10)
    local packages = "`packages'% Page formatting" + char(10)
	local packages = "`packages'\documentclass{article}" + char(10)
	local packages = "`packages'\usepackage[a4paper,margin=0.5in,landscape]{geometry}" + char(10)
    local packages = "`packages'\pagenumbering{gobble}" + char(10)
	local packages = "`packages'" + char(10)
    local packages = "`packages'% Typography and characters" + char(10)
    local packages = "`packages'\usepackage[activate={true,nocompatibility},final,tracking=true,kerning=true,spacing=true,factor=1100,stretch=10,shrink=10]{microtype}" + char(10)
	local packages = "`packages'\usepackage{lmodern}" + char(10)
    local packages = "`packages'\usepackage[english]{babel}" + char(10)
    local packages = "`packages'\usepackage[T1]{fontenc}" + char(10)
    local packages = "`packages'" + char(10)
    local packages = "`packages'% Table formatting" + char(10)
	local packages = "`packages'\usepackage{threeparttable}" + char(10)
	local packages = "`packages'\usepackage{booktabs}" + char(10)
	local packages = "`packages'\usepackage{multirow}" + char(10)
	local packages = "`packages'\usepackage{makecell}" + char(10)
    local packages = "`packages'\renewcommand{\arraystretch}{1.05} % set row height" + char(10)
    local packages = "`packages'\usepackage{siunitx} " + char(10)
    local packages = "`packages'\sisetup{ " + char(10)
    local packages = "`packages'    input-symbols = () [] \{ \}," + char(10)
    local packages = "`packages'    input-decimal-markers = {.}," + char(10)
    local packages = "`packages'    table-space-text-pre = -," + char(10)
    local packages = "`packages'    table-space-text-post = \sym{***}," + char(10)
    local packages = "`packages'    table-align-text-post = false," + char(10)
    capture confirm variable firm_auto, exact // hartz table needs some extra space due to column headers
    if !_rc { 
        local packages = "`packages'    table-column-width=3.6em," + char(10)
    }
    capture confirm variable dqsts, exact // ALM has three digit coefficients! (and if the variable dqsts is in the data, we're in a ALM table)
    if !_rc { 
        local packages = "`packages'    table-format=3.3," + char(10)
        local packages = "`packages'    table-column-width=3.6em" + char(10)
    }
    else { 
        local packages = "`packages'    table-format=1.2" + char(10)
    }
    local packages = "`packages'}" + char(10)
	local packages = "`packages'" + char(10)
    local packages = "`packages'% Math, symbol and number formatting" + char(10)
	local packages = "`packages'\usepackage{amsmath}" + char(10)
	local packages = "`packages'\def\sym#1{\ifmmode^{#1}\else\(^{#1}\)\fi} % define \sym (significance stars)" + char(10)
    local packages = "`packages'\def\stimes{\kern -0.25em $\times$ \kern -0.25em} % define \sstimes (\times with smaller kerning and in text env)" + char(10)
    local packages = "`packages'\def\mrmc#1{\multirow{2}{*}{\makecell[tl]{#1}}} % define \mrcmc to make two row var labels" + char(10)
    local packages = "`packages'\def\nsk{\noalign{\smallskip}} % define \nsk to make a small skip between rows in the label" + char(10)
    local packages = "`packages'\def\yes{{Yes}} % define \yes (FE indicator)" + char(10)
    local packages = "`packages'\def\no{{No}}	% define \no (FE indicator)" + char(10)
    local packages = "`packages'" + char(10)

    local begindocument = "`begindocument'%------- Begin Document ------- %" + char(10)
	local begindocument = "`begindocument'\begin{document}" + char(10)
	local begindocument = "`begindocument'" + char(10)


    local begintable = "`begintable'%------- Begin Table ------- %"
    local begintable = "`begintable'" + char(10)
	local begintable = "`begintable'\begin{table}[htbp]" + char(10) 
    local begintable = "`begintable'\centering" + char(10)
    local begintable = "`begintable'\small" + char(10)
    local begintable = "`begintable'\begin{threeparttable}" + char(10)
    local begintable = "`begintable'" + char(10)

    if "`m'" == "" { 
		local m "@M" // #number of columns via esttab
	}
    local begintabular = "`begintabular'%------- Begin Tabular ------- %"
    local begintabular = "`begintabular'" + char(10)
	local begintabular = "`begintabular'\begin{tabular}{@{}l*{`m'}{S}}" + char(10) 
    local begintabular = "`begintabular'\toprule" + char(10)
    local begintabular = "`begintabular'" + char(10)

    local predepvarinfo ""
	if "`showdepvarinfo'" == "showdepvarinfo" {
		local predepvarinfo "Dependent variable"
	}
	if "`depvar'" != "none" {
		local depvarinfo "`predepvarinfo' &\multicolumn{@M}{c}{`depvar'}\\ \cmidrule(lr){2-\numexpr @M + 1\relax} "
	}
	else {
		local depvarinfo ""
	}
    
	if `"`rawaddheader'"' != "" {
		local x = strlen(`"`rawaddheader'"')
		local rawaddheader = substr(`"`rawaddheader'"',14,`=`x'-14')
		di `"`rawaddheader'"'
	}
    if `"`depvarlist'"' != "" {
		local x = strlen(`"`depvarlist'"')
		local y = substr(`"`depvarlist'"',12,`=`x'-12')

		local cdepvar1 "`predepvarinfo'"
		local cdepvar2 ""
		local start 2
		foreach element of local y {
			local var : word 1 of `element'
			local len : word 2 of `element'
			if "`len'" == "" {
				local len 1
			}
			local cdepvar1 "`cdepvar1' & \multicolumn{`len'}{c}{`var'}"
			local end = `start' + `len' -1
			local cdepvar2 "`cdepvar2'\cmidrule(lr){`start' - `end'}"
			local start = `end' + 1
		}
		local depvarinfo "`cdepvar1' \\ `cdepvar2'"
	}

    * Posthead: midrule
	local midrule = "`midrule'\noalign{\vskip 0.4mm}" + char(10) 
    local midrule = "`midrule'\midrule " + char(10)
    local midrule = "`midrule'\noalign{\vskip 0.4mm}" + char(10)

    * Esttab...

    * Postfoot: endtabular, tablenote, endtable, enddocument
    
    local endtabular = "`endtabular'" + char(10)
    local endtabular = "`endtabular'%------- End Tabular ------- %"
    local endtabular = "`endtabular'" + char(10)
	local endtabular = "`endtabular'\bottomrule" + char(10) 
    local endtabular = "`endtabular'\end{tabular}" + char(10)
    local endtabular = "`endtabular'" + char(10)

    local note_pvalues " Significance levels at *10\%, **5\%, ***1\%."
    if missing(`"$output_nostar"') {
        di "Output_nostar macro is undefined; defaulting to only outputting a star version of the table"
        global output_nostar = 0
    }
    if ($output_nostar) { 
        local note_pvalues ""
    }
    if `"`notes'"' != "" {
        local tablenote = "`tablenote'%------- Table Note ------- %"
        local tablenote = "`tablenote'" + char(10)
        local tablenote = "`tablenote'\begin{tablenotes}[para,flushleft]" + char(10) 
        local tablenote = "`tablenote'Note.-- " + `"`notes'"'  + char(10) 
        local tablenote = "`tablenote'`note_pvalues'" + char(10) 
        local tablenote = "`tablenote'\end{tablenotes}" + char(10)
        local tablenote = "`tablenote'" + char(10)
	}

    local endtable = "`endtable'%------- End Table ------- %"
    local endtable = "`endtable'" + char(10)
	local endtable = "`endtable'\end{threeparttable}" + char(10) 
    local endtable = "`endtable'\end{table}" + char(10)
    local endtable = "`endtable'" + char(10)
  
    local enddocument = "`enddocument'%------- End Document ------- %" + char(10)
    local enddocument = "`enddocument'" + char(10)
	local enddocument = "`enddocument'\end{document}" + char(10)
	local enddocument = "`enddocument'" + char(10)

	esttab `anything' `using', `options' star(* 0.1 ** 0.05 *** 0.01) prehead(`packages'`begindocument'`begintable'`begintabular'`depvarinfo'`rawaddheader') posthead(`midrule') postfoot(`"`endtabular'`tablenote'`endtable'`enddocument'"') 
    if $output_nostar { 
        local using: subinstr local using ".tex" "_nostar.tex", all
        esttab `anything' `using', nostar `options' prehead(`packages'`begindocument'`begintable'`begintabular'`depvarinfo'`rawaddheader') posthead(`midrule') postfoot(`"`endtabular'`tablenote'`endtable'`enddocument'"') 
    }
end program
